package org.sws.trigger.http;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.sws.domain.activity.model.valobj.UserAccountCountFlagVO;
import org.sws.domain.activity.service.quota.IRaffleActivityAccountQuotaService;
import org.sws.domain.strategy.model.entity.RaffleAwardEntity;
import org.sws.domain.strategy.model.entity.RaffleFactorEntity;
import org.sws.domain.strategy.model.entity.StrategyAwardEntity;
import org.sws.domain.strategy.model.valobj.RuleWeightVO;
import org.sws.domain.strategy.service.IRaffleAward;
import org.sws.domain.strategy.service.IRaffleRule;
import org.sws.domain.strategy.service.IRaffleStrategy;
import org.sws.domain.strategy.service.armory.IStrategyArmory;
import org.sws.trigger.api.IRaffleStrategyService;
import org.sws.trigger.dto.*;
import org.sws.types.enums.ResponseCode;
import org.sws.types.exception.AppException;
import org.sws.types.model.Response;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author sws
 * @Date 2025/3/11 17:17
 * @description: 抽奖http接口
 */
@Slf4j
@RestController
@RequestMapping("/api/bigmarket/raffle/strategy/")
@CrossOrigin("${app.config.cross-origin}")
public class RaffleStrategyController implements IRaffleStrategyService {

    @Resource
    private IRaffleAward raffleAward;
    @Resource
    private IRaffleStrategy raffleStrategy;
    @Resource
    private IStrategyArmory strategyArmory;
    @Resource
    private IRaffleRule raffleRule;
    @Resource
    private IRaffleActivityAccountQuotaService activityAccountQuotaService;

    /**
     * 策略装配，将策略信息装配到缓存中
     * @param strategyId 策略ID
     * @return 装配结果
     */
    @GetMapping("strategyArmory")
    @Override
    public Response<Boolean> strategyArmory(@RequestParam Long strategyId) {
        try {
            log.info("抽奖策略装配开始 strategyId：{}", strategyId);
            boolean armoryStatus = strategyArmory.assembleLotteryStrategy(strategyId);
            Response<Boolean> response = Response.success(armoryStatus);
            log.info("抽奖策略装配完成 strategyId：{} response: {}", strategyId, JSON.toJSONString(response));
            return response;
        } catch (AppException e) {
            log.error("抽奖策略装配失败 strategyId：{}", strategyId, e);
            return Response.fail(e);
        }catch (Exception e){
            log.error("抽奖策略装配失败 strategyId：{}", strategyId, e);
            return Response.fail();
        }
    }


    /**
     * 查询奖品列表
     * @param requestDTO 活动信息
     * @return 奖品列表
     */
    @PostMapping("queryRaffleAwardList")
    @Override
    public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO requestDTO) {
        try {
            // 1. 参数校验
            if (StringUtils.isBlank(requestDTO.getUserId()) || null == requestDTO.getActivityId() || StringUtils.isEmpty(requestDTO.getAwardLockCheckFlag())) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            // 查询奖品配置
            List<StrategyAwardEntity> strategyAwardEntities = raffleAward.queryRaffleStrategyAwardListByActivityId(requestDTO.getActivityId());
            // 获取规则配置的规则树id集合
            String[] treeIds = strategyAwardEntities.stream()
                    .map(StrategyAwardEntity::getRuleModels)
                    .filter(ruleModel -> ruleModel != null && !ruleModel.isEmpty())
                    .toArray(String[]::new);
            // 查询规则配置 - 获取奖品的解锁限制，抽奖N次后解锁
            Map<String, Integer> ruleLockCountMap = raffleRule.queryAwardRuleLockCount(treeIds);
            // 获取 用户抽奖账户额度中抽奖次数
            Integer partakeCount = activityAccountQuotaService.queryRaffleActivityAccountPartakeCount(requestDTO.getActivityId(), requestDTO.getUserId(),requestDTO.getAwardLockCheckFlag());

            List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>(strategyAwardEntities.size());
            for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
                Integer awardRuleLockCount = ruleLockCountMap.get(strategyAward.getRuleModels());
                raffleAwardListResponseDTOS.add(RaffleAwardListResponseDTO.builder()
                        .awardId(strategyAward.getAwardId())
                        .awardTitle(strategyAward.getAwardTitle())
                        .awardSubtitle(strategyAward.getAwardSubtitle())
                        .sort(strategyAward.getSort())
                        .awardRuleLockCount(awardRuleLockCount)
                        .isAwardUnlock(null == awardRuleLockCount || partakeCount >= awardRuleLockCount)
                        .waitUnLockCount(null == awardRuleLockCount || awardRuleLockCount <= partakeCount ? 0 : awardRuleLockCount - partakeCount)
                        .build());
            }
            // 返回结果
            return Response.success(raffleAwardListResponseDTOS);
        } catch (Exception e) {
            log.error("查询抽奖奖品列表配置失败 activityID：{}", requestDTO.getActivityId(), e);
            return Response.fail();
        }
    }

    /**
     * 随机抽奖接口
     * @param requestDTO 请求参数 {"strategyId":1000001}
     * @return 抽奖结果
     */
    @PostMapping("randomRaffle")
    @Override
    public Response<RaffleStrategyResponseDTO> randomRaffle(@RequestBody RaffleStrategyRequestDTO requestDTO) {
        try {
            log.info("随机抽奖开始 strategyId: {}", requestDTO.getStrategyId());
            // 调用抽奖接口
            RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder()
                    .userId("system")
                    .strategyId(requestDTO.getStrategyId())
                    .build());
            // 封装返回结果
            Response<RaffleStrategyResponseDTO> response = Response.success(RaffleStrategyResponseDTO.builder()
                    .awardId(raffleAwardEntity.getAwardId())
                    .awardIndex(raffleAwardEntity.getSort())
                    .build());
            log.info("随机抽奖完成 strategyId: {} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(response));
            return response;
        } catch (AppException e) {
            log.error("随机抽奖失败 strategyId：{} {}", requestDTO.getStrategyId(), e.getInfo());
            return Response.fail(e);
        } catch (Exception e) {
            log.error("随机抽奖失败 strategyId：{}", requestDTO.getStrategyId(), e);
            return Response.fail();
        }
    }

    /**
     * 查询权重奖品配置列表
     * @param request 请求对象
     * @return 奖品列表
     */
    @GetMapping("queryRaffleStrategyRuleWeight")
    @Override
    public Response<List<RaffleStrategyRuleWeightResponseDTO>> queryRaffleStrategyRuleWeight(RaffleStrategyRuleWeightRequestDTO request) {
        if (StringUtils.isBlank(request.getUserId()) || null == request.getActivityId()) {
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        try {
            // 查询用户抽奖总次数
            Integer accountPartakeTotalCount = activityAccountQuotaService.queryRaffleActivityAccountPartakeCount(request.getActivityId(), request.getUserId(), UserAccountCountFlagVO.TOTAL.getCode());
            // 查询活动策略规则权重
            List<RaffleStrategyRuleWeightResponseDTO> raffleStrategyRuleWeightList = new ArrayList<>();
            List<RuleWeightVO> ruleWeightVOList = raffleRule.queryAwardRuleWeightByActivityId(request.getActivityId());
            for (RuleWeightVO ruleWeightVO : ruleWeightVOList) {
                // 转换对象
                List<RaffleStrategyRuleWeightResponseDTO.StrategyAward> strategyAwards = new ArrayList<>();
                List<RuleWeightVO.Award> awardList = ruleWeightVO.getAwardList();
                for (RuleWeightVO.Award award : awardList) {
                    RaffleStrategyRuleWeightResponseDTO.StrategyAward strategyAward = new RaffleStrategyRuleWeightResponseDTO.StrategyAward();
                    strategyAward.setAwardId(award.getAwardId());
                    strategyAward.setAwardTitle(award.getAwardTitle());
                    strategyAwards.add(strategyAward);
                }
                // 封装对象
                RaffleStrategyRuleWeightResponseDTO raffleStrategyRuleWeightResponseDTO = new RaffleStrategyRuleWeightResponseDTO();
                raffleStrategyRuleWeightResponseDTO.setRuleWeightCount(ruleWeightVO.getWeight());
                raffleStrategyRuleWeightResponseDTO.setStrategyAwards(strategyAwards);
                raffleStrategyRuleWeightResponseDTO.setUserActivityAccountTotalUseCount(accountPartakeTotalCount);
                raffleStrategyRuleWeightList.add(raffleStrategyRuleWeightResponseDTO);
            }
            return Response.success(raffleStrategyRuleWeightList);
        } catch (Exception e) {
            log.error("查询权重奖品配置列表失败 userId:{} activityId:{}", request.getUserId(), request.getActivityId(), e);
            return Response.fail();
        }
    }
}
